# coding: utf-8
from datetime import datetime
from django.db import models
from lib.common import BasicManager
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from services.datamodel.role.models import Role
import json
from project.settings import USER_LEVEL
from apps.student.share import app_logger
import collections


class ModelManagerSetMeal(BasicManager):

    def create(self, datas, del_id=None):
        if not datas:
            return False
        try:
            set_meal = json.loads(datas)
            self.filter(special_status=0).all().delete()
            for v in set_meal:
                if int(v) in [USER_LEVEL.LEVEL_SHENG, USER_LEVEL.LEVEL_SHI, USER_LEVEL.LEVEL_QU,
                              USER_LEVEL.LEVEL_ENDORSEMENT, USER_LEVEL.LEVEL_OPERATOR, USER_LEVEL.LEVEL_PLATINUM]:
                    for vs in set_meal[v]:
                        for k in vs:
                            for ks in vs[k]:
                                self.update_or_create(goods_id=ks, types=v, serial_number=k, defaults={'nums': vs[k][ks]})
            return True
        except Exception as e:
            app_logger.error(e)
            return False

    def get_meal(self, special_status=None):
        result = self.filter(is_show=1).values("is_show", "types", "nums", "goods_id", "goods__card_name",
                                               "serial_number", "id", "special_status")
        if special_status:
            result = result.filter(special_status=0)
        set_meal = collections.defaultdict(list)
        for v in result:
            set_meal[v['types']].append({'nums': v['nums'], 'serial_number': v['serial_number'], 'types': v['types'],
                                         'goods_id': v['goods_id'], 'id': v['id'], 'name': v['goods__card_name'],
                                         'special_status': v['special_status']})
        # aggregates = collections.defaultdict(list)
        # for k in set_meal:
        #     for v in set_meal[k]:
        #         aggregates[k].append({v['serial_number']: {v['goods_id']: v['nums']}})
        return set_meal


class SetMeal(models.Model):
    sort = models.IntegerField("排序", default=0, blank=True)
    is_show = models.PositiveSmallIntegerField("是否显示", default=1, blank=True)  # 1:展示  0:不展示
    types = models.PositiveSmallIntegerField("类型", default=1)  # 区分级别套餐 比如：1代表省代套餐  2代表
    nums = models.IntegerField("套餐内数量", default=1)  # 该套餐内的某个产品的规定数额
    goods = models.ForeignKey(Role)  # 关联role商品表
    serial_number = models.PositiveSmallIntegerField("套餐序号", default=1)
    special_status = models.PositiveSmallIntegerField("特殊展示", default=0, blank=True)  # 该字段是为了特殊要求，不如总平台展示，但是代理平台不展示
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerSetMeal()

    class Meta:
        verbose_name = '套餐'
        verbose_name_plural = verbose_name
        db_table = "momself_set_meal"


mm_SetMeal = SetMeal.objects
